package com.masterrabbit.mcslf.third;


import com.masterrabbit.common.core.web.domain.AjaxResult;
import com.masterrabbit.mcslf.pojo.Images;
import com.masterrabbit.mcslf.service.ImagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/images")
public class ImagesController {
    @Autowired
    private ImagesService imagesService;
    /**
     * 上传图片
     * @param files
     * @return R
     */
    @PostMapping("/upload")
    public AjaxResult uploadImages(@RequestParam("files") MultipartFile[] files) {
        List<Images> imageList = new ArrayList<>();
        Integer parentId = null;
        try {
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                InputStream inputStream = file.getInputStream();
                // 上传到OSS
                String imageUrl = OSSUtil.upload(fileName, inputStream);
                // 构建图片对象
                Images images = new Images();
                images.setParentId(parentId);
                images.setImageUrl(imageUrl);
                imagesService.save(images);
                // 第一张图片设为父图片
                if (i == 0) {
                    parentId = images.getImageId();
                    images.setParentId(parentId);
                    imagesService.updateById(images);
                }
                imageList.add(images);
            }
            return AjaxResult.success(imageList);
        } catch (IOException e) {
            return AjaxResult.error("图片上传失败: " + e.getMessage());
        }
    }

}